<script setup lang="ts">
import { ref, watch, nextTick, onMounted, type PropType } from 'vue';
import { Menu } from '@ark-ui/vue/menu';
import { useElementHover, useWindowSize } from '@vueuse/core';
import JumpTo from './JumpTo.vue';

const props = defineProps({
  menubarItems: {
    type: Array as PropType<Record<string, any>[]>,
    default: () => [],
  },

  routerMode: {
    type: Boolean,
    default: false,
  },
});

const menubarItemsEl = ref<Element | null>(null);
const overflowItems = ref<any[]>([]);
const menuHoverStates = ref<{ [key: string]: boolean }>({});
const overflowMenuEl = ref(null);
const { width: windowWith } = useWindowSize();
const isOverflowMenuHovered = useElementHover(overflowMenuEl, { delayEnter: 200, delayLeave: 200 });
const handleMenuHover = (barId: string, isHovered: boolean) => {
  menuHoverStates.value[barId] = isHovered;
};

const checkOverflowItems = () => {
  if (menubarItemsEl.value) {
    const listItems = menubarItemsEl.value.querySelectorAll('li');
    listItems.forEach(item => {
      item.style.display = '';
    });
    if (listItems.length === 0) {
      overflowItems.value = [];
      return;
    }
    let itemsPerRow = 0;
    let prevOffsetLeft = listItems[0].offsetLeft;
    for (let i = 1; i < listItems.length; i++) {
      if (listItems[i].offsetLeft < prevOffsetLeft) {
        itemsPerRow = i;
        break;
      }
      prevOffsetLeft = listItems[i].offsetLeft;
    }
    if (itemsPerRow === 0) {
      overflowItems.value = [];
      return;
    }
    listItems.forEach((item, index) => {
      item.style.display = index >= itemsPerRow ? 'none' : '';
    });
    overflowItems.value = props.menubarItems.slice(itemsPerRow - 2);
  }
};

onMounted(() => {
  watch([windowWith, () => props.menubarItems], () => { nextTick(checkOverflowItems) }, { immediate: true });
});
</script>

<template>
  <div class="h-full min-w-180 flex gap-20" ref="menubarEl">
    <ul class="h-full flex flex-wrap gap-x-20 overflow-hidden" ref="menubarItemsEl">
      <template v-if="props.routerMode">
        <li class="h-64 flex items-center">
          <RouterLink to="/" class="whitespace-nowrap px-16 no-underline hover:text-color-primary-2 focus-visible:outline-unset">
            {{ $t('common.header.nav1') }}
          </RouterLink>
        </li>
        <li class="h-64 flex items-center">
          <RouterLink to="/explore" class="whitespace-nowrap px-16 no-underline hover:text-color-primary-2 focus-visible:outline-unset">
            {{ $t('common.header.nav2') }}
          </RouterLink>
        </li>
      </template>
      <template v-else>
        <li class="h-64 flex items-center">
          <a href="/" class="whitespace-nowrap px-16 no-underline hover:text-color-primary-2 focus-visible:outline-unset" target="_blank">
            {{ $t('common.header.nav1') }}
          </a>
        </li>
        <li class="h-64 flex items-center">
          <a href="/explore" class="whitespace-nowrap px-16 no-underline hover:text-color-primary-2 focus-visible:outline-unset" target="_blank">
            {{ $t('common.header.nav2') }}
          </a>
        </li>
      </template>

      <li
        class="h-64 flex items-center"
        v-for="item in menubarItems"
        :key="item.barId"
        @mouseenter="handleMenuHover(item.barId, true)"
        @mouseleave="handleMenuHover(item.barId, false)"
      >
        <JumpTo :menubar-item="item" :router-mode="props.routerMode" class="whitespace-nowrap px-16 text-#292929 no-underline hover:text-color-primary-2" v-if="!item.children" />

        <Menu.Root v-else :positioning="{ placement: 'bottom', gutter: 0 }" :open="menuHoverStates[item.barId]">
          <Menu.Trigger as-child>
            <div class="h-full flex cursor-default items-center">
              <div class="cursor-pointer px-16 text-#292929 leading-24">{{ item.barName }}</div>
            </div>
          </Menu.Trigger>
          <Menu.Positioner>
            <Menu.Content as-child>
              <div class="z--1 rounded-6 bg-white px-8 py-10 shadow-[0_5px_15px_0_rgba(0,0,0,0.15)] focus-visible:outline-unset">
                <Menu.Item :value="group.barName" as-child v-for="group in item.children " :key="group.barId">
                  <JumpTo :menubar-item="group" :router-mode="props.routerMode" class="block min-w-128 whitespace-nowrap rounded-4 px-8 py-6 text-center text-14 font-400 leading-32 hover:bg-#f7f7f7" />
                </Menu.Item>
              </div>
            </Menu.Content>
          </Menu.Positioner>
        </Menu.Root>
      </li>
    </ul>

    <div ref="overflowMenuEl" class="flex-shrink-0 cursor-pointer" v-if="overflowItems.length">
      <Menu.Root :open="isOverflowMenuHovered" lazy-mount close-on-select :positioning="{ placement: 'bottom', gutter: 0 }">
        <Menu.Trigger as-child>
          <div class="h-full flex items-center">
            <div class="text-14 text-#292929 leading-24">...</div>
          </div>
        </Menu.Trigger>
        <Menu.Positioner>
          <Menu.Content as-child>
            <div class="rounded-6 bg-white px-8 py-10 shadow-[0_5px_15px_0_rgba(0,0,0,0.15)] focus-visible:outline-unset">
              <div v-for="item in overflowItems" :key="item.barId">
                <Menu.Item value="item.barName" as-child v-if="!item.children">
                  <JumpTo :menubar-item="item" :router-mode="props.routerMode" class="block min-w-128 whitespace-nowrap rounded-4 px-8 py-6 text-center text-14 font-400 leading-32 hover:bg-#f7f7f7" />
                </Menu.Item>

                <Menu.Root v-else :positioning="{ placement: 'right-end', gutter: 8 }">
                  <Menu.TriggerItem as-child>
                    <div class="min-w-128 cursor-pointer whitespace-nowrap rounded-4 px-8 py-6 text-center text-14 font-400 leading-32 hover:bg-#f7f7f7">
                      {{ item.barName }}
                    </div>
                  </Menu.TriggerItem>
                  <Menu.Positioner>
                    <Menu.Content as-child>
                      <div class="z--1 rounded-6 bg-white px-8 py-10 shadow-[0_5px_15px_0_rgba(0,0,0,0.15)] focus-visible:outline-unset">
                        <Menu.Item :value="group.barName" as-child v-for="group in item.children " :key="group.barId">
                          <JumpTo :menubar-item="group" :router-mode="props.routerMode" class="block min-w-128 whitespace-nowrap rounded-4 px-8 py-6 text-center text-14 font-400 leading-32 hover:bg-#f7f7f7" />
                        </Menu.Item>
                      </div>
                    </Menu.Content>
                  </Menu.Positioner>
                </Menu.Root>
              </div>
            </div>
          </Menu.Content>
        </Menu.Positioner>
      </Menu.Root>
    </div>
  </div>
</template>

<style lang="scss" scoped>
</style>
